import { defineStore } from 'pinia'
import { ref } from 'vue'
import { logout as logoutApi } from '@/api/user'
interface UserInfo {
  id: string
  username: string
  avatar?: string
  email?: string
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<UserInfo | null>(null)
    const token = ref<string>('')

    const setUserInfo = (info: UserInfo) => {
      userInfo.value = info
    }

    const setToken = (t: string) => {
      token.value = t
    }

    const logout = async () => {
      const res: any = await logoutApi()
      if (res.code === 200) {
        userInfo.value = null
        token.value = ''
      }
    }

    return {
      userInfo,
      token,
      setUserInfo,
      setToken,
      logout,
    }
  },
  {
    // 启用持久化
    persist: {
      enabled: true,
      strategies: [
        {
          key: 'admin_user',
          storage: localStorage,
          // 只持久化 token 和 userInfo
          paths: ['token', 'userInfo'],
        },
      ],
    },
  }
)
